using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using UnityEngine.Networking;
using Newtonsoft.Json;
using UnityEngine;

namespace Paradogs2
{
    public class HttpUtils
    {

        // 发送 GET 请求的方法
        public static async Task<string> GetAsync(string url)
        {
            try
            {
                using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
                {
                    // 发送请求并等待完成
                    var asyncOperation = webRequest.SendWebRequest();
                    while (!asyncOperation.isDone)
                    {
                        await Task.Yield();
                    }

                    // 检查请求结果
                    if (webRequest.result == UnityWebRequest.Result.Success)
                    {
                        // 请求成功，返回响应文本
                        return webRequest.downloadHandler.text;
                    }
                    else
                    {
                        // 请求失败，抛出异常
                        throw new Exception($"请求失败: {webRequest.error}");
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并抛出
                throw new Exception($"发生异常: {ex.Message}", ex);
            }
        }

        // 发送 POST 请求的方法，使用 params 接收多个键值对
        public static async Task<T> PostAsync<T>(string url, params (string Key, object Value)[] dataPairs)
        {
            try
            {
                // 将传入的键值对数组转换为 Dictionary
                var data = new Dictionary<string, object>();
                foreach (var (Key, Value) in dataPairs)
                {
                    data[Key] = Value;
                }

                // 准备要发送的数据，将 Dictionary 序列化为 JSON 字符串
                string jsonData = JsonConvert.SerializeObject(data);
                byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonData);

                using (UnityWebRequest webRequest = new UnityWebRequest(url, "POST"))
                {
                    // 设置请求体
                    UploadHandlerRaw uploadHandler = new UploadHandlerRaw(bodyRaw);
                    webRequest.uploadHandler = uploadHandler;

                    // 设置响应处理方式
                    DownloadHandlerBuffer downloadHandler = new DownloadHandlerBuffer();
                    webRequest.downloadHandler = downloadHandler;

                    // 设置请求头
                    webRequest.SetRequestHeader("Content-Type", "application/json");

                    // 发送请求并等待完成
                    var asyncOperation = webRequest.SendWebRequest();
                    while (!asyncOperation.isDone)
                    {
                        await Task.Yield();
                    }

                    // 检查请求结果
                    if (webRequest.result == UnityWebRequest.Result.Success)
                    {
                        // 请求成功，返回响应文本
                        return JsonConvert.DeserializeObject<AjaxResult<T>>(webRequest.downloadHandler.text).data;
                    }
                    else
                    {
                        // 请求失败，抛出异常
                        throw new Exception($"请求失败: {webRequest.error}");
                    }
                }
            }
            catch (Exception ex)
            {
                // 捕获异常并抛出
                Debug.LogError(ex.Message);
                throw new Exception($"发生异常: {ex.Message}", ex);
            }
        }
    }
}